import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { getHerosList } from '@/api/hero'


export interface IndexModelType {
    namespace: 'hero';
    state: {
        heroList: Array<any>,
        pageInfo?: {
            pagenum: number,
            pagesize: number,
            total: number
        }
    };
    effects: {
        getHeroList: Effect;
    };
    reducers: {
        // save: Reducer<IndexModelState>;
        // 启用 immer 之后
        setHeroList: ImmerReducer<IndexModelType>;
    };
    // subscriptions: { setup: Subscription };
}

const HeroModel: IndexModelType = {
    namespace: 'hero',
    state: {
        heroList: [],
        pageInfo: {
            pagenum: 1,
            pagesize: 5,
            total: 5
        }
    },
    // 发起异步任务   
    effects: {
        //   action里的内容    redux-saga
        *getHeroList(action, { put }) {
            const res = yield getHerosList({
                pagenum: 1,
                pagesize: 5
            })
            yield put({
                type: "setHeroList", res: res.data, pageInfo: {
                    pagenum: 1,
                    pagesize: 5,
                    total: res.total
                }
            })

            console.log(res)
        },
    },
    reducers: {
        // 启用 immer 之后
        setHeroList(state: any, action) {
            let newState = { ...state }
            // 加 key
            let heroList = action.res
            heroList.forEach((item: any) => item.key = item._id)
            newState.heroList = heroList
            newState.pageInfo = action.pageInfo
            return newState
        }
    },
    // subscriptions: {
    //     setup({ dispatch, history }) {
    //         if (history.location.pathname === "/hero/list") {
    //             dispatch({ type: "getHeroList" })
    //         }
    //     },
    // },
};

export default HeroModel;